package com.example.a13001.shoppingmalltemplate.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.example.a13001.shoppingmalltemplate.MainActivity;
import com.example.a13001.shoppingmalltemplate.R;
import com.example.a13001.shoppingmalltemplate.alipay.PayResult;
import com.example.a13001.shoppingmalltemplate.base.AppConstants;
import com.example.a13001.shoppingmalltemplate.base.BaseActivity;
import com.example.a13001.shoppingmalltemplate.modle.Alipay;
import com.example.a13001.shoppingmalltemplate.modle.WechatPay;
import com.example.a13001.shoppingmalltemplate.mvpview.OnLinePayView;
import com.example.a13001.shoppingmalltemplate.presenter.OnLinePayPredenter;
import com.example.a13001.shoppingmalltemplate.utils.MyUtils;
import com.example.a13001.shoppingmalltemplate.utils.Utils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class OnLinePayActivity extends BaseActivity {

    @BindView(R.id.tv_title_center)
    TextView tvTitleCenter;
    @BindView(R.id.tv_onlinepay_orderid)
    TextView tvOnlinepayOrderid;
    @BindView(R.id.tv_onlinepay_totalprice)
    TextView tvOnlinepayTotalprice;
    @BindView(R.id.tv_onlinepay_payway)
    TextView tvOnlinepayPayway;
    @BindView(R.id.tv_onlinepay_yue)
    TextView tvOnlinepayYue;
    @BindView(R.id.et_onlinepay_pwd)
    EditText etOnlinepayPwd;
    @BindView(R.id.btn_onlinepay_sure)
    Button btnOnlinepaySure;
    @BindView(R.id.rl_root)
    RelativeLayout rlRoot;
    @BindView(R.id.ll_onlinepay_yue)
    LinearLayout llOnlinepayYue;
    @BindView(R.id.tv_onlinepay_line1)
    TextView tvOnlinepayLine1;
    @BindView(R.id.tv_onlinepay_content)
    TextView tvOnlinepayContent;
    @BindView(R.id.ll_onlinepay_pwd)
    LinearLayout llOnlinepayPwd;
    @BindView(R.id.tv_onlinepay_line2)
    TextView tvOnlinepayLine2;
    @BindView(R.id.tv_onlinepay_youryue)
    TextView tvOnlinepayYouryue;
    @BindView(R.id.ll_onlinepay_bank)
    LinearLayout llOnlinepayBank;

    private String totalprice;
    private OnLinePayPredenter onLinePayPredenter = new OnLinePayPredenter(OnLinePayActivity.this);
    private String code;
    private String timestamp;
    private String orderNumber;
    private static final String TAG = "OnLinePayActivity";
    private int payid;

    private static final String APP_ID = "wxc3137b88302dd911";
    private IWXAPI api;
    private static final int SDK_PAY_FLAG = 1;
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            @SuppressWarnings("unchecked")
            PayResult payResult = new PayResult((java.util.Map<String, String>) msg.obj);
            /**
             对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
             */
            String resultInfo = payResult.getResult();// 同步返回需要验证的信息
            String resultStatus = payResult.getResultStatus();
            Log.e(TAG, "handleMessage: "+resultStatus+resultInfo+payResult.getMemo());
            // 判断resultStatus 为9000则代表支付成功
            if (android.text.TextUtils.equals(resultStatus, "9000")) {
                // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                android.widget.Toast.makeText(OnLinePayActivity.this, "支付成功", android.widget.Toast.LENGTH_SHORT).show();
                startActivity(new Intent(OnLinePayActivity.this,OrderListActivity.class).putExtra("type","2"));
                finish();
                //EventBus.getDefault().post(new ThirdEvent("支付成功"));
                //Querendingdan.this.finish();
            } else {
                // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                android.widget.Toast.makeText(OnLinePayActivity.this, "支付失败", android.widget.Toast.LENGTH_SHORT).show();
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_on_line_pay);
        regToWx();
        ButterKnife.bind(this);

        initData();
    }

    /**
     * 注册到微信
     */
    private void regToWx() {
//        api= WXAPIFactory.createWXAPI(RechargeActivity.this,APP_ID,true);
        api = WXAPIFactory.createWXAPI(OnLinePayActivity.this, APP_ID, true);
        api.registerApp(APP_ID);
    }

    OnLinePayView onLinePayView = new OnLinePayView() {
        @Override
        public void onSuccessWechatPay(WechatPay wechatPay) {
            Log.e(TAG, "onSuccessWechatPay: " + wechatPay.toString());
            int status = wechatPay.getStatus();
            if (status > 0) {
                PayReq req = new PayReq();
                req.appId = wechatPay.getAppid();
                req.partnerId = String.valueOf(wechatPay.getPartnerid());
                req.prepayId = wechatPay.getPrepayid();
                req.nonceStr = wechatPay.getNonceStr();
                req.timeStamp = wechatPay.getTimeStamp();
                req.packageValue = "Sign=WXPay";
                req.sign = wechatPay.getPaySign();
                boolean b = api.sendReq(req);
//                                        Toast.makeText(RechargeActivity.this, "" + b, Toast.LENGTH_SHORT).show();
            } else {

            }
        }

        @Override
        public void onSuccessAliPay(Alipay alipay) {
            Log.e(TAG, "onSuccessAliPay: "+alipay.toString() );
            int status=alipay.getStatus();
            if (status>0){
                final String paySign = alipay.getPaySign();
                Runnable payRunnable = new Runnable() {
                    @Override
                    public void run() {
                        com.alipay.sdk.app.PayTask alipay = new PayTask(OnLinePayActivity.this);

                        java.util.Map<String, String> result = alipay.payV2(paySign, true);
                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };
                Thread payThread = new Thread(payRunnable);
                payThread.start();
            }else{

            }
        }

        @Override
        public void onError(String result) {
            Log.e(TAG, "onError: " + result.toString());
        }
    };

    /**
     * 初始化数据源
     */
    private void initData() {
        onLinePayPredenter.onCreate();
        onLinePayPredenter.attachView(onLinePayView);

        tvTitleCenter.setText("在线支付");

        String safetyCode = MyUtils.getMetaValue(OnLinePayActivity.this, "safetyCode");
        code = Utils.md5(safetyCode + Utils.getTimeStamp());
        timestamp = Utils.getTimeStamp();

        if (getIntent() != null) {
            orderNumber = getIntent().getStringExtra("orderNumber");
            totalprice = getIntent().getStringExtra("totalprice");
            payid = getIntent().getIntExtra("payid", -1);
        }
        tvOnlinepayOrderid.setText(orderNumber);
        tvOnlinepayTotalprice.setText("¥" + totalprice);
//        
        //返回支付模式，0 余额支付 1 货到付款 2 银行转账 3 邮局汇款 4 支付宝 5 微信支付 6 财付通 8 中国银联 9 银联电子支付
        switch (payid) {
            case 0:
                tvOnlinepayPayway.setText("余额支付");
                tvOnlinepayLine1.setVisibility(View.VISIBLE);
                tvOnlinepayLine2.setVisibility(View.VISIBLE);
                llOnlinepayYue.setVisibility(View.VISIBLE);
                llOnlinepayPwd.setVisibility(View.VISIBLE);
                llOnlinepayBank.setVisibility(View.GONE);
                tvOnlinepayYouryue.setText("您的余额:");
                btnOnlinepaySure.setText("立即支付");
                btnOnlinepaySure.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                    }
                });
                break;
            case 1:
                tvOnlinepayPayway.setText("货到付款");
                break;
            case 2:
                tvOnlinepayPayway.setText("银行转账");
                tvOnlinepayLine1.setVisibility(View.VISIBLE);
                tvOnlinepayLine2.setVisibility(View.VISIBLE);
                llOnlinepayYue.setVisibility(View.VISIBLE);
                llOnlinepayPwd.setVisibility(View.GONE);
                tvOnlinepayYouryue.setText("支付说明:");
                llOnlinepayBank.setVisibility(View.VISIBLE);
                btnOnlinepaySure.setText("会员中心");
                btnOnlinepaySure.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startActivity(new Intent(OnLinePayActivity.this,MainActivity.class).putExtra("type","onLinepay"));
//                        EventBus.getDefault().post("会员中心");
                    }
                });
                break;
            case 3:
                tvOnlinepayPayway.setText("邮局汇款");
                break;
            case 4:
                tvOnlinepayPayway.setText("支付宝");
                tvOnlinepayLine1.setVisibility(View.GONE);
                tvOnlinepayLine2.setVisibility(View.GONE);
                llOnlinepayYue.setVisibility(View.GONE);
                llOnlinepayPwd.setVisibility(View.GONE);
                llOnlinepayBank.setVisibility(View.GONE);
                btnOnlinepaySure.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
//                        Log.e(TAG, "onViewClicked: " + "=code==" + code + "=timestamp==" + timestamp + "=orderNumber==" + orderNumber + "=ip==" + MyUtils.getIPAddress(OnLinePayActivity.this));
                        onLinePayPredenter.doAlipay(AppConstants.COMPANY_ID, code, timestamp, orderNumber);


                    }
                });
                break;
            case 5:
                tvOnlinepayPayway.setText("微信支付");
                tvOnlinepayLine1.setVisibility(View.GONE);
                tvOnlinepayLine2.setVisibility(View.GONE);
                llOnlinepayYue.setVisibility(View.GONE);
                llOnlinepayPwd.setVisibility(View.GONE);
                llOnlinepayBank.setVisibility(View.GONE);
                btnOnlinepaySure.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Log.e(TAG, "onViewClicked: " + "=code==" + code + "=timestamp==" + timestamp + "=orderNumber==" + orderNumber + "=ip==" + MyUtils.getIPAddress(OnLinePayActivity.this));
                        onLinePayPredenter.wechatPay(AppConstants.COMPANY_ID, code, timestamp, orderNumber, MyUtils.getIPAddress(OnLinePayActivity.this));
                    }
                });
                break;
            case 6:
                tvOnlinepayPayway.setText("财付通");
                break;
            case 8:
                tvOnlinepayPayway.setText("中国银联");
                break;
            case 9:
                tvOnlinepayPayway.setText("银联电子支付");
                break;
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @OnClick({R.id.iv_title_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //返回
            case R.id.iv_title_back:
                onBackPressed();
                break;

        }
    }
}
